package cn.edu.zufe.mjt.schedule;

import javax.print.event.PrintJobListener;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.locks.LockSupport;

/**
 * @author 蒙锦涛
 * @date 2025/5/26
 */


public class ScheduleService {
    Trigger trigger = new Trigger();
    ExecutorService executorService = Executors.newFixedThreadPool(6);
    void schedule(Runnable task, long delay) {
        Job job = new Job();
        job.setTask(task);
        job.setStartTime(System.currentTimeMillis() + delay);
        job.setDelay(delay);
        trigger.jobList.offer(job);
        trigger.wakeUp();
    }
    // 等待合适的时间把任务扔进线程池
    private class Trigger {
        PriorityBlockingQueue<Job> jobList = new PriorityBlockingQueue<>();
        Thread thread = new Thread(()->{
            while (true) {
                while (jobList.isEmpty()) { // 用while循环避免虚假唤醒
                    LockSupport.park();
                }
                Job latelyJob = jobList.peek();
                if (latelyJob.getStartTime() < System.currentTimeMillis()) {
                    latelyJob = jobList.poll();
                    executorService.execute(latelyJob.getTask());
                    Job nextJob = new Job();
                    nextJob.setTask(latelyJob.getTask());
                    nextJob.setDelay(latelyJob.getDelay());
                    nextJob.setStartTime(System.currentTimeMillis() + nextJob.getDelay());
                    jobList.offer(nextJob);
                } else {
                    LockSupport.parkUntil(latelyJob.getStartTime());
                }
            }
        });
        {
            thread.start(); // 启动触发器线程
            System.out.println("触发器启动");
        }
        void wakeUp() {
            LockSupport.unpark(thread);
        }
    }

}
